package com.goodsogood.union.auth.thrfit.pool;

import java.util.concurrent.TimeUnit;

import org.apache.thrift.TServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.goodsogood.service.union.user.thrift.AuthService;
import com.goodsogood.service.union.user.thrift.UserMoneyService;
import com.goodsogood.service.union.user.thrift.UserService;
import com.goodsogood.thrift.pool.ThriftConnectionPool;
import com.goodsogood.thrift.pool.config.ThriftConnectionPoolConfig;
import com.goodsogood.thrift.pool.config.ThriftConnectionPoolConfig.TProtocolType;
import com.goodsogood.thrift.pool.connection.ThriftConnection;
import com.goodsogood.thrift.pool.exception.ThriftConnectionPoolException;
import com.goodsogood.union.auth.conf.LogConfiger;

@Component("userConnectionPool")
@Scope("singleton")
public class UserConnectionPool implements InitializingBean {

    static final Logger logger = LoggerFactory.getLogger(LogConfiger.APP);
    
	@Value("${thrift.server.user.serverInfo}")
	private String serverInfo;
	
	public static boolean DEBUG = false;

    private ThriftConnectionPool<TServiceClient> pool = null;
	private void init() {

		ThriftConnectionPoolConfig config = new ThriftConnectionPoolConfig(
		ThriftConnectionPoolConfig.ThriftServiceType.MULTIPLEXED_INTERFACE);
	    config.setConnectTimeout(30000);
	    config.setThriftProtocol(TProtocolType.JSON);
	    String[] hosts = serverInfo.split(",");
        //部署多服务
        for(int i = 0; i < hosts.length; i++) {
            String[] hostAndPort = hosts[i].split(":");
            String host = hostAndPort[0];
            int port = Integer.valueOf(hostAndPort[1]);
            logger.info("UserConnectionPool connecting... [" + host + ":" + port + "]");
            config.addThriftServer(host, port);
        }
	    config.addThriftClientClass("userService", UserService.Client.class);
	    config.addThriftClientClass("authService", AuthService.Client.class);
	    config.addThriftClientClass("userMoneyService", UserMoneyService.Client.class);

	    config.setMaxConnectionPerServer(10);
	    config.setMinConnectionPerServer(5);
	    config.setIdleMaxAge(10, TimeUnit.SECONDS);
	    config.setMaxConnectionAge(2);
	    config.setLazyInit(false);
	    config.setAcquireIncrement(2);
	    config.setAcquireRetryDelay(2000);

	    config.setAcquireRetryAttempts(1);
	    config.setMaxConnectionCreateFailedCount(1);
	    config.setConnectionTimeoutInMs(30000);
	    
		try {
			config.check();
		} catch (ThriftConnectionPoolException e) {
		    e.printStackTrace();
		}
		
		try {
			pool = new ThriftConnectionPool<>(config);
		} catch (ThriftConnectionPoolException e) {
			e.printStackTrace();
		}
	}
	
	public ThriftConnection<TServiceClient> getConn() {
		
		if(pool == null) {
			init();
		}
		ThriftConnection<TServiceClient> connection = null;
	    try {
	      connection = pool.getConnection();
	    } catch (ThriftConnectionPoolException e) {
	      e.printStackTrace();
	    }
	    return connection;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		init();
	}
	
}
